/*
 * Powered By 
 * Since 2010 - 2016
 */

package com.rf.business.control;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.ezmorph.object.DateMorpher;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.rf.business.model.AutoRelease;
import com.rf.business.model.CarArchives;
import com.rf.business.model.CarDriverArchives;
import com.rf.business.model.CardRelease;
import com.rf.business.model.Declaration;
import com.rf.business.service.AutoReleaseService;
import com.rf.business.service.CarArchivesService;
import com.rf.business.service.CarDriverArchivesService;
import com.rf.business.service.CardReleaseService;
import com.rf.business.service.DeclarationService;
import com.rf.sys.frm.BaseController;
import com.rf.sys.model.User;
import com.rf.sys.service.CommonService;
import com.rf.sys.service.DepUserService;
import com.rf.sys.service.UserService;
import com.rf.sys.utils.ConfigUtils;
import com.rf.sys.utils.DateUtils;
import com.rf.sys.utils.JsonUtils;
import com.rf.sys.utils.PageUtils;
import com.rf.sys.utils.UuidUtil;

@Controller
@RequestMapping("/bus/declaration")
public class DeclarationController extends BaseController{
	/**
	 * 日志
	 */
	private static Logger log = LoggerFactory.getLogger(DeclarationController.class);
	private static final long serialVersionUID = -120161117110153088L;
	
	@Resource
	private DeclarationService declarationService;
	@Resource
	private CommonService commonService;
	@Resource
	private CarArchivesService carArchivesService;
	@Resource
	private CarDriverArchivesService carDriverArchivesService;
	@Resource
	private UserService userService;
	@Resource
	private DepUserService depUserService;
	@Resource
	private CardReleaseService cardReleaseService;
	@Resource
	private AutoReleaseService autoReleaseService;
	
	/**
	 * 初始化页面信息
	 * @param request,response
	 * @return ModelAndView
	 * @throws ServletException,IOException
	 */
	@RequestMapping(value = "index")
    public ModelAndView index (HttpServletRequest request, HttpServletResponse response) throws Exception{
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("/business/declaration/list");
		return modelAndView; 
    }
    
    /**
	 * 搜索页面信息
	 * @param Page,request,response
	 * @return JSON
	 * @throws ServletException,IOException
	 */
    @RequestMapping(value = "query")
    @ResponseBody
    public void query (PageUtils pageUtils, Declaration declaration, HttpServletRequest request, HttpServletResponse response ) throws Exception{
    	//获取分页、查询参数，进行数据封装
    	List<String> list = new ArrayList<String>();
    	//获取当前登陆用户信息
    	Session session = SecurityUtils.getSubject().getSession();
    	boolean isAdmin = (Boolean) session.getAttribute("isAdmin");
    	//判断用户是否具有管理员角色,没有则查询部门下的用户清单
    	if(!isAdmin){
    		String depid = (String)session.getAttribute("depSessionId");
        	list = depUserService.getUserListByDepID(depid);
    	}
    	Map searchMap = declarationService.getDeclarationPage(declaration, pageUtils, list);
    	super.responsePrint(request, response, JsonUtils.mapToJson(searchMap));
    }
    
    /**
     * 编辑页面初始化
     * @param request,response
	 * @return ModelAndView
	 * @throws ServletException,IOException
     */
    @RequestMapping(value = "edit")
    public ModelAndView edit(HttpServletRequest request, HttpServletResponse response ) throws Exception{
    	ModelAndView modelAndView = new ModelAndView();
		String id = request.getParameter("id");
		String cardId = request.getParameter("cardId");//放行卡号
		String foreignCarNo = request.getParameter("foreignCarNo");//外国车牌
		String chineseCarNo = request.getParameter("chineseCarNo");//中国车牌
		String entryTime = request.getParameter("entryTime");//入境时间
		Declaration declaration = new Declaration();
		if(id != null && !id.equals("")){
			declaration = declarationService.getDeclarationByID(id);
			modelAndView.addObject("declaration", declaration);
			String et = DateUtils.dateToString(declaration.getEntryTime(), ConfigUtils.DATEFORMATER1);
			String pst = DateUtils.dateToString(declaration.getPlanStayTime(), ConfigUtils.DATEFORMATER1);
			modelAndView.addObject("entryTime", et);
			modelAndView.addObject("planStayTime", pst);
	        modelAndView.setViewName("/business/declaration/view");
		}else{
			CarArchives carArchives = new CarArchives();
			String carNo = "";
			if(foreignCarNo!=null && !foreignCarNo.equals("")){
				carNo = foreignCarNo;
			}else if(chineseCarNo!=null && !chineseCarNo.equals("")){
				carNo = chineseCarNo;
			}
			carArchives.setCarNo(carNo);
			//获取该备案号下备案信息
			List<CarArchives> list = carArchivesService.getCarArchives(carArchives);
			if(list.size()>0){
				carArchives = list.get(0);
			}
			declaration.setSerialNo(commonService.getSerialNo(2));//流水号
			declaration.setCardId(cardId);//放行卡号
			declaration.setCarRegistrationNo(carArchives.getArchiveNo());//车辆备案号
			declaration.setForeignCarNo(foreignCarNo);//外国车牌
			declaration.setChineseCarNo(chineseCarNo);//中国车牌
			declaration.setCarNationality(carArchives.getCarNationality());//车辆国籍
			declaration.setEngineNo(carArchives.getEngineNo());//发动机号
			declaration.setCarFrameNo(carArchives.getCarFrameNo());//车架号码
			declaration.setCarModel(carArchives.getCarModel());//车辆型号
			declaration.setCarColor(carArchives.getCarColor());//车辆颜色
			declaration.setCarMasterName(carArchives.getCarOwner());//企业/车主名称
			declaration.setTelephone(carArchives.getCarOwnerTel());//联系方式
			modelAndView.addObject("entryTime", entryTime);//入境时间
			modelAndView.addObject("declaration", declaration);
			//modelAndView.addObject("endDate",carArchives.getEndDate());//失效日期
			Date endDate = carArchives.getEndDate();
			Date date = new Date();
			long value = (endDate.getTime() - date.getTime())/(1000*60*60*24);
			if(value >= 0 && value <= 10){
				modelAndView.addObject("value",1);
			}else if(value < 0){
				modelAndView.addObject("value",2);
			}else{
				modelAndView.addObject("value",3);
			}
	        modelAndView.setViewName("/business/declaration/edit");
		}
        return modelAndView; 
    }
    
    /**
     * 保存数据信息
     * @param Declaration,request,response
	 * @return ModelAndView
	 * @throws ServletException,IOException
     */
    @RequestMapping(value = "save")
    public void save (HttpServletRequest request, HttpServletResponse response ) throws Exception{
    	JSONObject returnObj = new JSONObject();
    	//获取当前登陆用户信息
    	Session session = SecurityUtils.getSubject().getSession();
		User user = (User)session.getAttribute("userSession");
    	String params = request.getParameter("data");
    	JSONObject jsonObject = JSONObject.fromObject(params);
    	JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[]{ConfigUtils.DATEFORMATER1,ConfigUtils.DATEFORMATER1})); 
    	Declaration declaration  = (Declaration) JSONObject.toBean(jsonObject, Declaration.class);
    	
		if(declaration !=null && declaration.getId()!=null && !declaration.getId().equals("")){
			//修改
			declarationService.updateDeclaration(declaration);
		}else{
			//新增
			CarArchives carArchives = new CarArchives();
			carArchives.setArchiveNo(declaration.getCarRegistrationNo());
			//获取该备案号下备案信息
			List<CarArchives> list = carArchivesService.getCarArchives(carArchives);
			if(list.size()>0){
				carArchives = list.get(0);
			}
			declaration.setCarNationality(carArchives.getCarNationality());//车辆国籍
			declaration.setEngineNo(carArchives.getEngineNo());//发动机号
			declaration.setCarFrameNo(carArchives.getCarFrameNo());//车架号码
			declaration.setCarModel(carArchives.getCarModel());//车辆型号
			declaration.setCarColor(carArchives.getCarColor());//车辆颜色
			declaration.setCarMasterName(carArchives.getCarOwner());//企业/车主名称
			declaration.setTelephone(carArchives.getCarOwnerTel());//联系方式
			
			//获取驾驶员信息
			CarDriverArchives  carDriverArchives  = carDriverArchivesService.getCarDriverArchivesByID(declaration.getCdaId());
			declaration.setDriverName(carDriverArchives.getName());
			declaration.setDriverArchiveNo(carDriverArchives.getArchiveNo());
			
			declaration.setId(UuidUtil.get32UUID());
			declaration.setState(ConfigUtils.ENABLESTATE);
			declaration.setCreateUser(user.getId());
			declaration.setCreateTime(new Date());
			declarationService.addDeclaration(declaration);
			
			//申报单保存之后将旅行社接车状态变为“已接车”;判断放行开关是否打开
			CardRelease  cardRelease = cardReleaseService.getCardReleaseByID(declaration.getCardId());
			cardRelease.setIsMeetCar(ConfigUtils.YJCSTATE);
			cardRelease.setMeetCarDate(new Date());
			cardRelease.setPortCheckState(ConfigUtils.DFXSTATE);
			cardRelease.setCustomCheckState(ConfigUtils.DFXSTATE);
			cardRelease.setGateCheckState(ConfigUtils.DFXSTATE);
			List<AutoRelease> autoReleaseList = autoReleaseService.getAutoRelease();
			for(AutoRelease autoRelease:autoReleaseList){
				String extImp =  autoRelease.getEntryExitType();
				String auto = autoRelease.getIsAuto();
				if("bjrj".equals(extImp) && ConfigUtils.YESFX.equals(auto)){
					cardRelease.setBorderCheckDate(new Date());
					cardRelease.setBorderCheckState(ConfigUtils.YFXSTATE);
				}else if("gjrj".equals(extImp) && ConfigUtils.YESFX.equals(auto)){
					cardRelease.setNationCheckDate(new Date());
					cardRelease.setNationCheckState(ConfigUtils.YFXSTATE);
				}else{
					cardRelease.setBorderCheckState(ConfigUtils.DFXSTATE);
					cardRelease.setNationCheckState(ConfigUtils.DFXSTATE);
				}
			}
			cardReleaseService.updateCardRelease(cardRelease);
		}
		returnObj.element("message", "success");//成功
		super.responseJson(request, response, returnObj.toString());
    }
    
    /**
     * 删除数据信息
     * @param request,response
	 * @return JSON
	 * @throws ServletException,IOException
	 */
    @RequestMapping(value = "delete")
    @ResponseBody
    public void delete (HttpServletRequest request, HttpServletResponse response) throws Exception{
    	JSONObject returnObj = new JSONObject();
    	String ids = request.getParameter("ids");
    	declarationService.deleteDeclaration(ids);
		returnObj.element("message", "success");//成功
		super.responseJson(request, response, returnObj.toString());
    }
    
    /**
     * 更新数据状态
     * @param declaration,request,response
	 * @return JSON
	 * @throws ServletException,IOException
	 */
    @RequestMapping(value = "updateState")
    @ResponseBody
    public void updateState (Declaration declaration, HttpServletRequest request, HttpServletResponse response) throws Exception{
    	JSONObject returnObj = new JSONObject();
    	declarationService.updateDeclaration(declaration);
		returnObj.element("message", "success");//成功
		super.responseJson(request, response, returnObj.toString());
    }
}


